import 'package:backend.core/core/domain/entities/app_store/app_store_transaction.dart';
import 'package:backend.purchases/domain/entities/app_store_api/app_store_api_one_time_purchased_item_transaction.dart';
import 'package:backend.purchases/domain/entities/app_store_api/app_store_api_purchased_subscription_transaction.dart';
import 'package:backend.purchases/domain/entities/app_store_api/app_store_api_transaction.dart';
import 'package:backend.purchases/domain/helpers/app_store/create_app_store_one_time_purchased_item_transaction_from_api_one.dart';
import 'package:backend.purchases/domain/helpers/app_store/create_app_store_purchased_subscription_transaction_from_api_one.dart';

abstract class CreateAppStoreTransactionFromApiOne {
  AppStoreTransaction call({
    required AppStoreApiTransaction apiTransaction,
    required String appStoreUserId,
  });
}

class CreateAppStoreTransactionFromApiOneImpl implements CreateAppStoreTransactionFromApiOne {
  const CreateAppStoreTransactionFromApiOneImpl({
    required CreateAppStoreOneTimePurchasedItemTransactionFromApiOne
        createAppStoreOneTimePurchasedItemTransactionFromApiOne,
    required CreateAppStorePurchasedSubscriptionTransactionFromApiOne
        createAppStoreSubscriptionTransactionFromApiOne,
  })  : _createAppStoreOneTimePurchasedItemTransactionFromApiOne =
            createAppStoreOneTimePurchasedItemTransactionFromApiOne,
        _createAppStoreSubscriptionTransactionFromApiOne =
            createAppStoreSubscriptionTransactionFromApiOne;

  final CreateAppStoreOneTimePurchasedItemTransactionFromApiOne
      _createAppStoreOneTimePurchasedItemTransactionFromApiOne;
  final CreateAppStorePurchasedSubscriptionTransactionFromApiOne
      _createAppStoreSubscriptionTransactionFromApiOne;

  @override
  AppStoreTransaction call({
    required AppStoreApiTransaction apiTransaction,
    required String appStoreUserId,
  }) {
    if (apiTransaction is AppStoreApiSubscriptionTransaction) {
      final apiSubscriptionTransaction = apiTransaction;

      final subscriptionTransaction = _createAppStoreSubscriptionTransactionFromApiOne(
        apiPurchasedSubscriptionTransaction: apiSubscriptionTransaction,
        appStoreUserId: appStoreUserId,
      );

      return subscriptionTransaction;
    }

    if (apiTransaction is AppStoreApiOneTimePurchasedItemTransaction) {
      final apiOneTimePurchasedItemTransaction = apiTransaction;

      final oneTimePurchasedItemTransaction =
          _createAppStoreOneTimePurchasedItemTransactionFromApiOne(
        apiOneTimePurchasedItemTransaction: apiOneTimePurchasedItemTransaction,
        appStoreUserId: appStoreUserId,
      );

      return oneTimePurchasedItemTransaction;
    }

    throw UnimplementedError();
  }
}
